package task

import (
	"fmt"
	"net/url"
	"os"
	"path/filepath"
	"sync"

	"github.com/cheggaaa/pb/v3"
)

type DownloadTask struct {
	URL           string
	TargetPath    string
	CurrentSize   int64
	TotalSize     int64
	Completed     bool
	Retries       int
	MaxRetries    int
	Bar           *pb.ProgressBar
	DownloadedURL *sync.Map
}

// 初始化下载任务
func InitTasks(urls []string, outputDir string, maxRetries int, downloadedURLs *sync.Map) ([]*DownloadTask, error) {
	tasks := make([]*DownloadTask, 0, len(urls))

	for _, u := range urls {
		parsedURL, err := url.Parse(u)
		if err != nil {
			fmt.Printf("无效的URL %s: %v\n", u, err)
			continue
		}

		// 为每个URL创建一个子目录
		urlDir := filepath.Join(outputDir, parsedURL.Hostname())
		if err := os.MkdirAll(urlDir, 0755); err != nil {
			fmt.Printf("创建URL目录失败 %s: %v\n", urlDir, err)
			continue
		}

		// 确定目标文件路径
		fileName := filepath.Base(parsedURL.Path)
		if fileName == "" || fileName == "." || fileName == "/" || fileName == "//" {
			fileName = "index.html"
		}

		// 初始化下载任务
		task := &DownloadTask{
			URL:           u,
			TargetPath:    filepath.Join(urlDir, fileName),
			MaxRetries:    maxRetries,
			DownloadedURL: downloadedURLs,
		}
		// fmt.Printf("InitTasks: task.DownloadedURL = %v\n", task.DownloadedURL)
		tasks = append(tasks, task)
	}
	return tasks, nil
}
